package com.adtech.adms.commons.web.intercepter;

import org.apache.log4j.Logger;

import com.adtech.core.exception.BaseException;
import com.adtech.core.exception.ErrorCode;
import com.adtech.core.exception.ErrorMessage;
import com.adtech.core.exception.ServiceException;
import com.adtech.core.exception.SystemException;
import com.adtech.core.web.action.AjaxResult;
import com.adtech.core.web.action.BaseAction;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 
 * 处理异常
 * @author Dormin 
 * @since 2011-11-10 O
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class ExceptionInterceptor extends BaseInterceptor {

	private static final long serialVersionUID = -6342795821580321655L;
	private static final String AJAX_LOAD_DATA = "ajaxLoadData";
	@Override
	public String intercept(ActionInvocation ai) {

		Logger log = Logger.getLogger(ai.getAction().getClass());
		String action = super.getActionClassName(ai);
		String method = super.getMethodName(ai);

		try{
			return ai.invoke();
		} catch (ServiceException e){
			log.warn(action + "." + method + "():" + e.getErrorMessage(), e);
			setActionResult(ai, e);
		} catch (SystemException e){
			log.error(action + "." + method + "():" + e.getErrorMessage(), e);
			setActionResult(ai, e);
		} catch (Exception e){
			log.error(action + "." + method + "():" + e.getMessage(), e);
			setActionResult(ai, e);
		}

		//如果Action方法执行过程中抛出异常，则更改返回值
		if (!super.iaAjaxRequest(ai)) {
			//非Ajax请求，将返回值改成ERROR
			return Action.ERROR;
		} else {
			//Ajax请求，将返回值改成SUCCESS
			if(method.equals(AJAX_LOAD_DATA)) {
				return Action.ERROR;
			}
			return Action.SUCCESS;
		}
	}

	private void setActionResult(ActionInvocation ai, Exception e){

		if (ai.getAction() instanceof BaseAction){
			BaseAction base = (BaseAction) ai.getAction();

			if (e instanceof BaseException){
				BaseException ex = (BaseException)e;
				base.setAjaxResult(AjaxResult.failed(ex.getErrorCode(), ex.getErrorMessage()));
				base.addActionError(ex.getErrorMessage());
			} else {
				base.setAjaxResult(AjaxResult.failed(ErrorCode.SYSTEM_UNKNOWN_ERROR));
				base.addActionError(ErrorMessage.get(ErrorCode.SYSTEM_UNKNOWN_ERROR));
			}
		}
	}

}
